package org.zzz.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.SqlSessionManager;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author ZZF
 * @Time 2021/04/18 15:54
 */
public class MybatisUtil {

//    private static SqlSessionFactory sqlSessionFactory;

//    static{
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = null;
//        try {
//            inputStream = Resources.getResourceAsStream(resource);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//    }
    private static SqlSessionManager sessionManager = null;
    static {
        try {
            InputStream inputStream = MybatisUtil.class.getClassLoader()
                    .getResourceAsStream("mybatis-config.xml");
            sessionManager = SqlSessionManager.newInstance(inputStream);
        } catch (Exception e) {
            throw new RuntimeException("the Configuration of Mybatis is not exist!");
        }
    }

    public static SqlSessionManager getSessionManager() {
        return sessionManager;
    }

//    public static SqlSession getSqlSession(){
//        return sqlSessionFactory.openSession(true);
//    }

    public static <T> T getMapper(Class<T> clazz) {
        return sessionManager.getMapper(clazz);
    }
    
}
